<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryParams"
        @submit.native.prevent
        label-width="65px"
      >
        <el-form-item label="变量名称" prop="name">
          <common-input v-model="queryParams.name" @enter="handleQuery">
          </common-input>
        </el-form-item>
        <el-form-item label="变量类型" prop="type">
          <el-select v-model="queryParams.type">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="数字" value="number"></el-option>
            <el-option label="字符" value="string"></el-option>
            <el-option label="日期" value="date"></el-option>
          </el-select>
        </el-form-item>
        <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept>
      </el-form>
    </common-search>
    <div slot="tools">
      <el-button
        type="primary"
        plain
        @click="handleAdd"
        icon="el-icon-plus"
        v-hasPermi="['system:variable:add']"
        >新增
      </el-button>
      <el-button
        type="danger"
        plain
        @click="handleDelete()"
        icon="el-icon-delete"
        :disabled="!showBatch"
        v-hasPermi="['system:variable:remove']"
        >批量删除
      </el-button>
    </div>
    <common-table
      slot="content"
      @selection-change="handleSelectionChange"
      v-loading="isLoading"
      :data="list"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="变量名称"
        align="left"
        show-overflow-tooltip
        prop="name"
      />
      <el-table-column
        label="变量类型"
        align="left"
        show-overflow-tooltip
        prop="type"
      >
        <template slot-scope="scope">
          {{
            scope.row.type === "number"
              ? "数字"
              : scope.row.type === "string"
              ? "字符"
              : "日期"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="默认值"
        align="left"
        prop="defaultValue"
        show-overflow-tooltip
      />
      <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      />
      <el-table-column
        label="变量描述"
        align="left"
        prop="variableDescribe"
        show-overflow-tooltip
      />

      <el-table-column label="操作" align="left" width="90">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="edit(scope.row)"
            v-hasPermi="['system:variable:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:variable:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-edit-dialog
      :visible="isShow"
      :title="isEdit ? '编辑全局变量' : '新增全局变量'"
      @cancel="cancel"
      @submit="submitForm"
      :button-loading="buttonLoading"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        :rules="rules"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="变量名称" prop="name">
              <common-input placeholder="请输入" v-model="form.name" />
            </el-form-item>
            <el-form-item label="变量类型" prop="type">
              <el-select v-model="form.type" clearable @change="changeType">
                <el-option label="数字" value="number"></el-option>
                <el-option label="字符" value="string"></el-option>
                <el-option label="日期" value="date"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="默认值"
              prop="defaultValue"
              :rules="form.type !== 'string' ? rules.defaultValue : []"
            >
              <common-input-number
                style="width: 100%"
                placeholder="请输入"
                v-if="form.type !== 'string' && form.type !== 'date'"
                :maxLength="16"
                v-model="form.defaultValue"
              ></common-input-number>
              <common-input
                placeholder="请输入"
                v-else
                v-model="form.defaultValue"
                :verify="false"
              />
            </el-form-item>
            <common-add-dept
              ref="commonAddDept"
              :deptListParams="departmentList"
              @getCheckedDeptId="getCheckedDeptId"
              :deptId="form.deptId"
            ></common-add-dept>
            <el-form-item label="变量描述" prop="variableDescribe">
              <common-input
                type="textarea"
                placeholder="请输入"
                v-model="form.variableDescribe"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
  </common-list>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import {
  globalList,
  globalAdd,
  globalEdit,
  globalDelete,
  deleteForCheck,
} from "@/api/screenConfig/global";
import { getSingleArray, getFullDept } from "@/utils/util";

export default {
  name: "index",
  mixins: [BaseList],
  data() {
    return {
      total: 0,
      queryParams: {
        name: null,
        type: null,
        defaultValue: null,
        deptIds: null,
        pageNum: 1,
        pageSize: 10,
      },
      isShow: false,
      isEdit: true,
      isLoading: false,
      buttonLoading: false,
      form: {
        name: null,
        type: "string",
        defaultValue: null,
        variableDescribe: null,
        deptId: null,
      },
      list: [],
      rules: {
        name: [{ required: true, message: "请输入变量名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择变量类型", trigger: "blur" }],
        defaultValue: [
          { required: true, message: "请输入默认值", trigger: "blur" },
        ],
        // deptId: [
        //   { required: true, message: '请选择组织', trigger: 'blur' }
        // ]
      },
      currentParent: 1,
      singleDeptList: [],
      departmentList: [],
    };
  },
  methods: {
    changeType() {
      console.log("1111");
      this.form.defaultValue = null;
    },
    getLoading() {
      this.isLoading = true;
    },
    getCheckedDeptId(val) {
      this.form.deptId = val;
    },
    getDeptList(list) {
      this.departmentList = list;
      this.singleDeptList = getSingleArray(list);
      this.getList();
    },
    getDeptId(val) {
      this.queryParams.deptIds = val;
    },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },

    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      this.$refs.commonDept.clearDept();
    },
    // 新增按钮
    handleAdd() {
      this.isShow = true;
      this.isEdit = false;
      this.reset();
    },
    // 删除按钮
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          globalDelete({ ids }).then((res) => {
            if (res && res.code === 200) {
              // if (this.queryParams.pageNum>1&&this.list.length===1){//如果不在第一页且数据只有一条
              //   this.queryParams.pageNum-=1
              // }
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              if (res.data) {
                // 为true代表被关联 不允许删除
                reject(res);
              } else {
                resolve(true);
              }
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //编辑
    edit(row) {
      this.id = row.id;
      Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
      if (this.form.type === "number")
        this.form.defaultValue = parseFloat(this.form.defaultValue);
      this.isEdit = true;
      this.isShow = true;
    },
    // 取消
    cancel() {
      this.isShow = false;
      this.reset();
    },
    reset() {
      this.form.name = "";
      this.form.type = "string";
      this.form.defaultValue = "";
      this.form.variableDescribe = "";
      this.form.deptId = "";
    },
    //提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const params = {
            ...this.form,
            id: this.id,
          };
          this.buttonLoading = true;
          if (this.isEdit) {
            globalEdit(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.isShow = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            globalAdd(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.isShow = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    getList(flag) {
      this.isLoading = true;
      globalList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows;
            this.list.forEach(
              (item) => (item.deptName = this.getDeptName(item.deptId || ""))
            );
            this.total = res && res.total ? res.total : 0;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => (this.isLoading = false));
    },
  },
  created() {
    // this.getList()
  },
};
</script>

<style scoped></style>
